<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '全部订单',
    navigationBarRightButton: {
      hide: true,
    },
  },
}
</route>
<template>
  <view
    class="w-full h-full bg-white overflow-hidden box-border"
    :style="{ paddingTop: safeAreaInsets?.top + 'px' }"
  >
    <view class="w-full h-full bg-#F6F6F8 pos-relative z-1">
      <wd-navbar @click-left="handleClickLeft">
        <template #title>
          <text class="text-gray-333 font-size-36 font-500">全部订单</text>
        </template>
        <template #left>
          <wd-icon
            name="chevron-left"
            class="text-gray-333 font-size-44"
            @click="pagesBack"
          ></wd-icon>
        </template>
      </wd-navbar>
      <view class="w-full h-full home-content">
        <view class="flex">
          <wd-tabs v-model="tab" :slidable-num="4" @change="handleTabChange">
            <block v-for="(item, index) in orderList" :key="index">
              <wd-tab :title="item.tabName">
                <view class="w-full tab-content">
                  <view class="w-full mg-t-20" v-for="(order, ri) in item.orderList" :key="ri">
                    <view class="w-full mg-t-20">
                      <view
                        class="p-x-28 flex justify-between items-center p-y-32 bg-white bdr-bottom-2-#F5F5F5"
                      >
                        <view class="font-400 text-gray-333 font-size-28">
                          订单号 {{ order.order_no }}
                        </view>
                        <view class="gont-400 font-size-28 text-blue-1">{{ order.status }}</view>
                      </view>
                    </view>
                    <view
                      class="w-full p-x-28 ps-t-32 bdr-top-#F5F5F5-2 bg-white"
                      @click="handleOrder(order)"
                    >
                      <view
                        class="flex justify-start ps-b-32"
                        v-for="(goods, gi) in order.orderGoods"
                        :key="gi"
                        @click="handleGoodsDetail(order)"
                      >
                        <view class="wr-160 hr-160 b-rd-8 overflow-hidden">
                          <view class="wr-160 hr-160">
                            <image width="100%" height="100%" :src="goods.pic" />
                          </view>
                        </view>
                        <view class="flex justify-between flex-col wr-510 mg-l-24">
                          <view class="flex justify-between">
                            <view>{{ goods.name }}</view>
                            <view>{{ goods.price }}</view>
                          </view>
                          <view class="flex justify-between font-size-26 text-gray-999">
                            <view>{{ goods.title }}</view>
                            <view>X {{ goods.num }}</view>
                          </view>
                        </view>
                      </view>
                    </view>
                    <view class="w-full p-x-28 bg-white ps-b-32" v-if="order.sendBack">
                      <view
                        class="flex justify-between items-center p-x-30 p-y-18 bg-#F7F7F9 b-rd-8"
                      >
                        <view class="font-size-32 text-blue-1 font-500 line-h-44">
                          <text>{{ order.sendBack.status }}</text>
                        </view>
                        <view class="font-size-28 text-gray-333 line-h-40 font-400">
                          <text>退回金额：</text>
                          <text class="text-blue-1 font-500">{{ order.sendBack.refund }}</text>
                        </view>
                      </view>
                    </view>
                    <view class="w-full p-x-24 p-y-24 bdr-top-2-#F5F5F5 bg-white flex justify-end">
                      <view class="wr-176 hr-72 mg-r-20" v-for="(btn, bi) in order.btns" :key="bi">
                        <wd-button type="primary" plain size="small" @click="handleBtn(btn, order)">
                          <text class="font-size-28">{{ btn.name }}</text>
                        </wd-button>
                      </view>
                    </view>
                  </view>
                </view>
              </wd-tab>
            </block>
          </wd-tabs>
        </view>
      </view>
    </view>
  </view>

  <wd-popup
    v-model="popupShow"
    lock-scroll
    position="bottom"
    :safe-area-inset-bottom="true"
    @close="closePopup"
  >
    <view class="w-full hr-716">
      <view class="w-full h-full p-x-28 p-y-32 border-box pos-relative">
        <view
          class="pos-absolute pos-top-28 pos-right-32 z-1 font-size-28 font-500 text-gray-999"
          @click="closePopup"
        >
          <wd-icon name="close"></wd-icon>
        </view>
        <view class="pos-absolute pos-top-102 pos-left-0 w-full hr-2 bg-#f5f5f5"></view>
        <view class="flex justify-start">
          <text class="font-size-32 font-500 text-gray-333">钱款去向</text>
        </view>
        <view class="flex justify-between items-center mg-t-55">
          <view class="font-size-40 text-blue-1 font-500">退款总金额</view>
          <view class="font-size-40 text-blue-1 font-500">
            <text class="font-size-28">￥</text>
            <text>100.00</text>
          </view>
        </view>
        <view class="flex justify-between items-center mg-t-36">
          <view class="font-size-32 text-gray-333 font-400">退回优惠</view>
          <view class="font-size-40 text-gray-333 font-500">
            <text class="font-size-28">￥</text>
            <text>20.00</text>
          </view>
        </view>
        <view class="flex justify-between items-center mg-t-36">
          <view class="font-size-32 text-gray-333 font-400">退回微信</view>
          <view class="font-size-40 text-gray-333 font-500">
            <text class="font-size-28">￥</text>
            <text>80.00</text>
          </view>
        </view>
        <view class="mg-t-24">
          <wd-steps vertical>
            <wd-step v-for="(item, index) in stepsList" space="24rpx" :key="index">
              <template v-slot:icon>
                <view
                  class="wr-38 hr-38 b-rd-21 b-solid-#D8D8D8-2 flex justify-center items-center"
                >
                  <view class="wr-20 hr-20 b-solid-#D8D8D8-2 b-rd-12"></view>
                </view>
              </template>
              <template v-slot:title>
                <view
                  class="text-gray-999 font-size-24 font-500 line-h-44 flex justify-start items-center"
                >
                  <text class="text-gray-333">{{ item.title }}</text>
                  <text class="mg-l-24">{{ item.titleTime }}</text>
                </view>
              </template>
              <template v-slot:description>
                <view class="font-size-24 font-500 line-h-44 flex justify-start items-center">
                  <text>{{ item.description }}</text>
                </view>
              </template>
            </wd-step>
          </wd-steps>
        </view>
      </view>
    </view>
  </wd-popup>
</template>

<script lang="ts" setup>
import { cancelOrder, getOrderList, confirmReceive } from '@/service/order/order'
import { orderPay } from '@/service/shop/shop'
import { useMessage } from 'wot-design-uni/components/wd-message-box'

defineOptions({
  name: 'AllOrder',
})
const { safeAreaInsets } = uni.getSystemInfoSync()
const handleClickLeft = () => {}
const pagesBack = () => {
  uni.switchTab({
    url: '/pages/home/person',
  })
}
// const OrderStatus: any = {
//   '0': '待付款',
//   '1': '已完成',
//   '2': '取消',
//   '3': '待收货',
//   '4': '待评价',
//   '5': '售后中',
//   '6': '售后通过待退货',
//   '7': '售后通过待退款',
//   '8': '退款中',
//   '9': '售后完成',
//   '10': '售后驳回',
//   '11': '无效订单',
// }
const tab = ref(0)
// 已完成：评价
// 待付款：取消订单、付款
// 待收货：查看物流、确认收获
// 待评价：评价
// 售后中、售后通过带退货、售后通过待退款、售后完成、售后驳回：查看订单
// 退款中，售后完成：钱款去向
const btnsHandleList: any = ref([
  {
    status: '已完成',
    btns: [
      { name: '查看物流', plain: true, value: 'logistics' },
      { name: '退款申请', plain: true, value: 'refund' },
    ],
  },
  {
    status: '待付款',
    btns: [
      { name: '取消订单', plain: true, value: 'cancel' },
      { name: '付款', plain: false, value: 'pay' },
    ],
  },
  {
    status: '待收货',
    btns: [
      { name: '查看物流', plain: true, value: 'logistics' },
      { name: '确认收货', plain: false, value: 'confirm' },
    ],
  },
  {
    status: '待评价',
    btns: [
      { name: '去评价', plain: true, value: 'comment' },
      { name: '查看物流', plain: true, value: 'logistics' },
    ],
  },
  {
    status: '待退货,售后通过待退货',
    btns: [{ name: '退货申请', plain: true, value: 'waitout' }],
  },
  {
    status: '售后中,售后通过待退款,售后完成,审核中,成功,退款中,待退款',
    btns: [
      { name: '查看订单', plain: true, value: 'lookorder' },
      { name: '查看物流', plain: true, value: 'logistics' },
    ],
  },
  {
    status: '退款中,售后完成,售后通过待退款',
    btns: [{ name: '查看物流', plain: true, value: 'logistics' }],
  },

  {
    status: '审核未通过,售后驳回,拒绝,失败',
    btns: [{ name: '重新申请', plain: true, value: 'apply' }],
  },
  // {
  //   status: '待退货',
  //   btns: [{ name: '退款申请', plain: true, value: 'refund' }],
  // },
])
const orderList: any = reactive([
  {
    tabName: '全部',
    tabValue: '-1',
    orderList: [],
  },
  {
    tabName: '待付款',
    tabValue: '0',
    orderList: [],
  },
  {
    tabName: '待收货',
    tabValue: '3',
    orderList: [],
  },
  {
    tabName: '待评价',
    tabValue: '4',
    orderList: [],
  },
  {
    tabName: '退款/售后',
    tabValue: '5',
    orderList: [],
  },
])
const handleBtn = (btn: any, item: any) => {
  item.handleType = btn.value
  switch (btn.value) {
    case 'cancel': // 取消订单
      cancelOrderData(item)
      break
    case 'pay': // 支付
      toConfirmPage('pay', item)
      break
    case 'logistics': // 查看物流
      toLogisticsPage(item)
      break
    case 'comment': // 评价
      toCommentPage()
      break
    case 'lookorder': // 查看订单
      toConfirmPage('lookorder', item)
      break
    case 'confirm': // 确认收货
      toConfirmPage('confirm', item)
      break
    case 'refund': // 申请退款
      toApplyRefundPage('refund', item)
      break
    // case 'reject': // 重新申请
    //   toApplyRefundPage('reject', item)
    // break
    case 'waitout': // 退货申请
      toApplyRefundPage('waitout', item)
      break
    // case 'moneyway':
    //   toOpenPage()
    // break
    case 'service':
      toServicePage()
      break
    case 'apply':
      toApplyRefundPage('apply', item)
      break
  }
}
const payTools = usePayTool()
const toConfirmPage = (type: string, item: any) => {
  if (type === 'pay') {
    orderPay({ id: item.id }).then((res: any) => {
      // 支付
      payTools.payTool(res.data)
    })
  } else if (type === 'lookorder') {
    handleGoodsDetail(item)
  } else if (type === 'confirm') {
    uni.showModal({
      content: '确定收货吗？',
      success: (res: any) => {
        if (res.confirm) {
          confirmReceive(item.id).then((res: any) => {
            uni.showToast({
              title: '收货成功',
              icon: 'success',
              duration: 2000,
            })
            getData()
          })
        }
      },
    })
  }
}
const message = useMessage()

const param: any = ref({
  id: '',
  reason: '',
})
const reason: any = ref('')
const cancelOrderData = (item: any) => {
  param.value.id = item.id
  message
    .prompt({
      title: '取消原因',
      inputValue: reason.value,
    })
    .then((resp) => {
      param.value.reason = resp.value
      cancelOrder(param.value).then((res: any) => {
        getData()
      })
    })
    .catch((res: any) => {
      console.log(res.action)
    })
}
const toCommentPage = () => {
  uni.navigateTo({
    url: '/pages/orders/appraise',
  })
}

const toApplyRefundPage = (type: string, item: any) => {
  item.handleType = type
  if (type === 'refund') {
    uni.setStorageSync('RefundDetails', JSON.stringify(item))
    uni.navigateTo({
      url: '/pages/orders/applyRefund',
    })
  } else if (type === 'apply') {
    uni.setStorageSync('RefundDetails', JSON.stringify(item))
    uni.navigateTo({
      url: '/pages/orders/applyRefund',
    })
  } else if (type === 'waitout') {
    console.log(item)
    uni.setStorageSync('GoodsDetails', JSON.stringify(item))
    uni.navigateTo({
      url: '/pages/orders/orderDetail',
    })
  }
}

const handleGoodsDetail = (goods: any) => {
  uni.setStorageSync('GoodsDetails', JSON.stringify(goods))
  uni.navigateTo({
    url: '/pages/orders/orderDetail',
  })
}
const toLogisticsPage = (item: any) => {
  uni.setStorageSync('OrderExpress', JSON.stringify(item))
  uni.navigateTo({
    url: '/pages/transport/orderTransport' + '?id=' + item.id + '&type=0', // 类型:0=普通订单,1=售后订单
  })
}
const toServicePage = () => {
  uni.navigateTo({
    url: '/pages/customer/service',
  })
}
const popupShow = ref(false)

// const popupOpen = () => {
//   popupShow.value = true
// }
const closePopup = () => {
  popupShow.value = false
}

const stepsList = ref([
  {
    title: '卖家退款',
    titleTime: '2021-12-19 19:48:30',
    status: 0,
    description: '卖家已退款，通常将原路返回',
  },
  {
    title: '到账成功',
    titleTime: '2021-12-19 19:48:30',
    status: 0,
    description: '钱款已退回至微信钱包，您可在微信-【钱包】-【账单】中查看。',
  },
])
onLoad((e: any) => {})
onShow(() => {
  const data: any = uni.getStorageSync('orderStatus')
  if (data) {
    const dataObj: any = JSON.parse(data)
    const orderIndex: any = orderList.findIndex((f: any) => {
      return f.tabName === dataObj.name
    })
    if (orderIndex > -1) {
      tab.value = orderIndex
    }
  } else {
    tab.value = 0
  }
  getData()
})
const clearList = () => {
  for (let i = 0; i < orderList.length; i++) {
    orderList[i].orderList = []
  }
}
const getData = () => {
  const param: any = {
    status: -1,
    page: 1,
  }
  if (tab.value === 0) {
    param.status = -1
  } else if (tab.value === 1) {
    param.status = 0
  } else if (tab.value === 2) {
    param.status = 3
  } else if (tab.value === 3) {
    param.status = 4
  } else if (tab.value === 4) {
    param.status = 5
  }
  getOrderList(param).then((res: any) => {
    const data: any = res.data.data
    clearList()
    for (let i = 0; i < data.length; i++) {
      const order: any = data[i]
      const findIndex: any = orderList.findIndex((f: any) => {
        return Number(f.tabValue) === Number(param.status)
      })
      const findItem: any = btnsHandleList.value.find((f: any) => {
        return f.status.indexOf(order.status) > -1
      })
      if (findItem) {
        order.btns = findItem.btns
      }
      if (findIndex > -1) {
        orderList[findIndex].orderList.push(order)
      }
    }
  })
}
const handleTabChange = (ev: any) => {
  tab.value = ev.index
  getData()
}
const handleOrder = (order: any) => {
  uni.setStorageSync('OrderDetails', JSON.stringify(order))
  if (order.status === '待收货') {
    uni.navigateTo({
      url: '/pages/orders/applyRefund',
    })
  }
}
</script>

<style scoped lang="scss">
.home-container {
  position: relative;
  z-index: 1;
}
.home-content {
  height: calc(100% - var(--wot-navbar-height, 88rpx));
  overflow: auto;
  background: #f6f6f8;
}
.box-linear-bg {
  background: linear-gradient(90deg, #ece7f6 0%, #dfdfff 100%);
}
.tab-content {
  box-sizing: border-box;
  height: calc(100vh - 88rpx - 84rpx - 42rpx);
  overflow: auto;
  background: #f6f6f8;
}
::v-deep .wd-button {
  width: 100% !important;
  height: 100% !important;
}
::v-deep .wd-tabs__nav-item {
  font-size: 28rpx !important;
  color: #312f2a !important;
}
::v-deep .wd-tabs {
  background-color: #f6f6f8;
}
::v-deep .wd-tabs.is-slide .wd-tabs__nav-item {
  padding: 0 30rpx;
}
::v-deep .wd-step__icon {
  display: flex;
  align-items: center;
  justify-content: center;
}
::v-deep .wd-step__content {
  padding-left: 10rpx !important;
}
</style>
